package com.efounder.email.dao;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.efounder.email.contacts.SortModel;
import com.efounder.email.db.ContactsDbHelper;
import com.efounder.email.db.DBManager;
import com.efounder.email.db.EmailsDbHelper;

/**
 * 联系人数据库操作
 * 
 * @author yqs
 * 
 */

public class ContactsDAO {

	private EmailsDbHelper contactsDbHelper;
	private SQLiteDatabase db;// 创建SQLiteDatabase对象

	public ContactsDAO(Context context) {
		contactsDbHelper = DBManager.getEmailsDbHelper(context);// 初始化DBgetOpenHelper对象
	}

	/**
	 * 添加联系人信息
	 * 
	 * @param sortModel
	 */

	public void add(SortModel sortModel) {
		db = contactsDbHelper.getWritableDatabase();// 初始化SQLiteDatabase对象
		db.execSQL("insert into contacts  values (?,?,?,?,?)", new Object[] {
				sortModel.contactId, sortModel.name, sortModel.number,
				sortModel.sortKey, sortModel.sortLetters });

	}

	/**
	 * 查找联系人
	 * 
	 * @return
	 */

	public ArrayList<SortModel> queryContacts() {
		db = contactsDbHelper.getWritableDatabase();// 初始化SQLiteDatabase对象
		// 查找并存储到Cursor类中
		Cursor cursor = db.rawQuery("select * from contacts", null);
		ArrayList<SortModel> allList = new ArrayList<SortModel>();
		// 遍历查询数据库
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			SortModel sortModel = new SortModel(cursor.getInt(cursor
					.getColumnIndex("_id")), cursor.getString(cursor
					.getColumnIndex("name")), cursor.getString(cursor
					.getColumnIndex("number")), cursor.getString(cursor
					.getColumnIndex("sortkey")), cursor.getString(cursor
					.getColumnIndex("sortletters")));
			allList.add(sortModel);
			// System.out.println(sortModel.name);
		}
		System.out.println("allList.size()：" + allList.size());
		return allList;
	}

	/**
	 * 获取联系人的数量
	 * 
	 * @return
	 */
	public long getCount() {
		db = contactsDbHelper.getWritableDatabase();// 初始化SQLiteDatabase对象
		Cursor cursor = db.rawQuery("select count(_id) from contacts", null);// 获取id的记录数
		if (cursor.moveToNext())// 判断Cursor中是否有数据
		{
			return cursor.getLong(0);// 返回总记录数
		}
		return 0;

	}

	/**
	 * 删除联系人
	 * 
	 * @param ids
	 */
	public void deleteContact(Integer... ids) {
		if (ids.length > 0)// 判断是否存在要删除的id
		{
			StringBuffer sb = new StringBuffer();// 创建StringBuffer对象
			for (int i = 0; i < ids.length; i++)// 遍历要删除的id集合
			{
				sb.append('?').append(',');// 将删除条件添加到StringBuffer对象中
			}
			sb.deleteCharAt(sb.length() - 1);// 去掉最后一个“,“字符
			db = contactsDbHelper.getWritableDatabase();// 初始化SQLiteDatabase对象
			// 执行删除联系人操作
			db.execSQL("delete from contacts where _id in (" + sb + ")",
					(Object[]) ids);
		}

	}

	/**
	 * 清楚联系人表中的全部数据
	 */
	public void deleteTableData() {
		db = contactsDbHelper.getWritableDatabase();
		db.execSQL("delete from contacts");
	}
}
